package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.build.ReplenishmentBuilder;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.Pager;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {
    @Autowired
    private UserService userService;
    @Autowired
    private VMService vmService;
    @Autowired
    private TaskDao taskDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TaskDetailsService taskDetailsService;
    @Autowired
    private MqttProducer mqttProducer;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    @Override
    @Transactional
    public Boolean create(TaskViewModel model) {
        //校验售货机状态
        checkVmStatus(model);
        //校验同一台设备是否有未完成同类型工单
        checkVmFinish(model);
        //生成工单编号
        String taskCode = initTaskCode();
        //判断工单类型是否正确
        checkProductType(model);
        //保存工单数据进数据库
        //1.封装工单
        TaskEntity taskEntity = new ReplenishmentBuilder(taskCode, model, userService, vmService)
                .buildBeanCopy().buildentity().buildUser().buildVm().bulid();
        save(taskEntity);
        //2.判断是否是补货工单
        if (model.getProductType() == VMSystem.TASK_TYPE_SUPPLY) {
            //保存补货工单
            saveDetails(model, taskEntity);
        }
        return true;
    }

    @Override
    public Boolean cancel(Long taskId, CancelTaskViewModel model) {
        //检查数据
        TaskEntity taskEntity = taskDao.selectById(taskId);
        if (taskEntity == null) {
            throw new LogicException("该工单不存在");
        }
        //工单状态是已取消或已完成，则抛出异常
        Integer taskStatus = taskEntity.getTaskStatus();
        if (taskStatus == VMSystem.TASK_TYPE_REPAIR || taskStatus == VMSystem.TASK_STATUS_FINISH) {
            throw new LogicException("该工单已完成或以取消");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        taskEntity.setDesc(model.getDesc());
        updateById(taskEntity);
        //修改工单状态
        return true;
    }

    /**
     * 接受工单
     *
     * @param taskId
     * @return
     */
    @Override
    public Boolean accept(Long taskId) {
        //检查数据
        TaskEntity taskEntity = taskDao.selectById(taskId);
        if (taskEntity == null) {
            throw new LogicException("该工单不存在");
        }
        //如果工单状态不是待处理，抛出异常。
        taskEntity = taskDao.selectById(taskId);
        if (taskEntity.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("工单非待处理状态");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        taskDao.updateById(taskEntity);

        return true;
    }

    /**
     * 完成工单
     *
     * @param taskId
     * @return
     */
    @Override
    public Boolean complete(Long taskId) {
        //检查数据
        TaskEntity taskEntity = taskDao.selectById(taskId);
        if (taskEntity == null) {
            throw new LogicException("该工单不存在");
        }
        taskEntity = taskDao.selectById(taskId);
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL || taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH) {
            throw new LogicException("该工单已完成或已取消");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        taskDao.updateById(taskEntity);
        //发送消息，修改售货机状态
        updateStatus(taskEntity,taskEntity.getTaskId());
        return true;
    }

    /**
     * 发送消息，修改售货机状态
     *
     * @param taskEntity
     */
    private void updateStatus(TaskEntity taskEntity,Long taskId) {
        Integer type = taskEntity.getProductTypeId();
        //判断工单类型
        if (type != VMSystem.TASK_TYPE_SUPPLY) {
            //创建发送类
            TaskCompleteContract contract = new TaskCompleteContract();
            contract.setTaskType(type);
            contract.setInnerCode(taskEntity.getInnerCode());
            //发送消息
            try {
                mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, JsonUtil.serialize(contract));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        } else {
            //创建发送类
            SupplyContract contract = new SupplyContract();
            //获取货道信息
            ArrayList<SupplyChannel> channels = getSupplyChannels(taskId);
            contract.setSupplyData(channels);
            contract.setInnerCode(taskEntity.getInnerCode());
            try {
                mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, JsonUtil.serialize(contract));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取货道信息
     * @param taskId
     * @return
     */
    private ArrayList<SupplyChannel> getSupplyChannels(Long taskId) {
        ArrayList<SupplyChannel> channels = new ArrayList<>();
        List<TaskDetailsEntity> list = taskDetailsService.getByTaskId(taskId);
        for (TaskDetailsEntity details : list) {
            SupplyChannel channel = new SupplyChannel();
            BeanUtils.copyProperties(details,channel);
            channel.setChannelId(details.getChannelCode());
            channel.setCapacity(details.getExpectCapacity());
            channels.add(channel);
        }
        return channels;
    }

    /**
     * 判断工单类型是否正确
     *
     * @param model
     */
    private void checkProductType(TaskViewModel model) {
        if (model.getProductType() == VMSystem.TASK_TYPE_SUPPLY && model.getDetails() == null || model.getDetails().size() == 0) {
            throw new LogicException("维护类工单没有补货明细表，请检查工单填写是否正确");
        }
    }

    /**
     * 保存补货工单
     *
     * @param model
     * @param taskEntity
     */
    private void saveDetails(TaskViewModel model, TaskEntity taskEntity) {
        List<TaskDetailsViewModel> details = model.getDetails();
        List<TaskDetailsEntity> list = new ArrayList<>();
        for (TaskDetailsViewModel detail : details) {
            TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
            taskDetailsEntity.setTaskId(taskEntity.getTaskId());
            list.add(taskDetailsEntity);
        }
        taskDetailsService.saveBatch(list, 10);
    }

    /**
     * 补货工单的创建（编写思路）
     * 格式为8位年月日+4位当日序号。
     *
     * @return
     */
    private String initTaskCode() {
        String format = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = "lkd_task_code" + format;
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().setIfAbsent(key, 0l, Duration.ofDays(1));
        }
        String taskCode = format + String.format("%04d", redisTemplate.opsForValue().increment(key, 1));
        //str.substring(a.length()-4, a.length())
        return taskCode;
    }

    /**
     * 校验同一台设备是否有未完成同类型工单
     *
     * @param model
     */
    private void checkVmFinish(TaskViewModel model) {
        Boolean flag = true;
        String innerCode = model.getInnerCode();
        LambdaQueryWrapper<TaskEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskEntity::getTaskCode, model.getInnerCode());
        wrapper.eq(TaskEntity::getProductTypeId, model.getProductType());
        List<TaskEntity> list = taskDao.selectList(wrapper);
        //通过流获取已完成的订单的数量
        List<TaskEntity> collect = list.stream().filter(taskEntity -> "4".equals(taskEntity.getTaskStatus().toString())
        ).collect(Collectors.toList());
        //已完成订单数量相同 则通过
        if (collect.size() != list.size()) {
            throw new LogicException("存在未完成订单");
        }
    }

    /**
     * 检查售货机状态
     *
     * @param model
     */
    private void checkVmStatus(TaskViewModel model) {
        int type = model.getProductType();
        //售货机状态(0:未投放;1-运营;3-撤机)
        //type=1为投放 2为补货 3为维修 4为撤机
        VmVO vm = vmService.getVMInfo(model.getInnerCode());
        if (vm == null) {
            throw new LogicException("该售货机不存在");
        }
        if (type == VMSystem.TASK_TYPE_DEPLOY && vm.getStatus() != VMSystem.VM_STATUS_NODEPLOY) {
            throw new LogicException("该售货机不为未投放状态，不能进行投放");
        }
        if (type == VMSystem.TASK_TYPE_SUPPLY && vm.getStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该售货机不为运营状态，不能进行补货");
        }
        if (type == VMSystem.TASK_TYPE_REPAIR && vm.getStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该售货机不为运营状态，不能进行维修");
        }
        if (type == VMSystem.TASK_TYPE_REVOKE && vm.getStatus() != VMSystem.VM_STATUS_REVOKE) {
            throw new LogicException("该售货机不为运营状态，不能进行撤机");
        }
    }


}
